/*
 * Copyright 2011 Sven Buschbeck.
 * 
 * This file is part of the ActiveObjects library.
 *
 *  ActiveObjects is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ActiveObjects is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.svenbuschbeck.gwt.ao.client.events;

import java.util.Collection;
import java.util.List;

import net.svenbuschbeck.gwt.ao.client.ActiveList;

import com.google.gwt.event.shared.GwtEvent;

/**
 * Represents the event of a value being added to something.
 * 
 * @param <T>
 *            the value being added
 */
public class ValueAddedEvent<T> extends GwtEvent<ValueAddedHandler<T>> {

	/**
	 * Handler type.
	 */
	private static Type<ValueAddedHandler<?>> TYPE;

	/**
	 * Fires a value added event on all registered handlers in the handler
	 * manager.If no such handlers exist, this method will do nothing.
	 * 
	 * @param <T>
	 *            the old value type
	 * @param source
	 *            the source of the handlers
	 * @param value
	 *            the value
	 */
	public static <T> void fire(HasValueAddedHandlers<T> source, T value) {
		if (getType() != null) {
			ValueAddedEvent<T> event = new ValueAddedEvent<T>(value);
			source.fireEvent(event);
		}
	}

	/**
	 * Fires value added event and adds to value to the given container, if not
	 * contained already. Use this call rather than making the decision to short
	 * circuit yourself for safe handling of null.
	 * 
	 * @param <T>
	 *            the value type
	 * @param activeCollection
	 *            the source of the handlers
	 * @param collection
	 *            the container, the value should be added to, may be null
	 * @param e
	 *            the value to be added to the given container, may be null
	 * @param valuesHaveToBeUnique
	 *            whether the value should only be added (and event fired) if
	 *            the value does not already exist in the set.
	 * @param valuesCanBeNull
	 *            if value must not be null to be added and event to be fired.
	 */
	public static <T> boolean addAndFireIfRequired(ActiveList<T> activeCollection, Collection<T> collection, T e,
		boolean valuesHaveToBeUnique, boolean valuesCanBeNull, Long maxSize) {
		if (shouldFire(activeCollection, collection, e, valuesHaveToBeUnique, valuesCanBeNull, maxSize)) {
			boolean gotAdded = collection.add(e);
			ValueAddedEvent<T> event = new ValueAddedEvent<T>(e);
			activeCollection.fireEvent(event);
			return gotAdded;
		}
		return false;
	}

	/**
	 * Fires value added event and adds to value to the given container, if not
	 * contained already. Use this call rather than making the decision to short
	 * circuit yourself for safe handling of null.
	 * 
	 * @param <T>
	 *            the value type
	 * @param activeCollection
	 *            the source of the handlers
	 * @param list
	 *            the container, the value should be added to, may be null
	 * @param e
	 *            the value to be added to the given container, may be null
	 * @param valuesHaveToBeUnique
	 *            whether the value should only be added (and event fired) if
	 *            the value does not already exist in the set.
	 * @param valuesCanBeNull
	 *            if value must not be null to be added and event to be fired.
	 */
	public static <T> boolean addAndFireIfRequired(ActiveList<T> activeCollection, List<T> list, T e, int index,
		boolean valuesHaveToBeUnique, boolean valuesCanBeNull, Long maxSize) {
		if (shouldFire(activeCollection, list, e, index, valuesHaveToBeUnique, valuesCanBeNull, maxSize)) {
			int sizeBefore = list.size();
			list.add(index, e);
			ValueAddedEvent<T> event = new ValueAddedEvent<T>(e);
			activeCollection.fireEvent(event);
			return sizeBefore != list.size();
		}
		return false;
	}

	/**
	 * Gets the type associated with this event.
	 * 
	 * @return returns the handler type
	 */
	public static Type<ValueAddedHandler<?>> getType() {
		if (TYPE == null) {
			TYPE = new Type<ValueAddedHandler<?>>();
		}
		return TYPE;
	}

	/**
	 * Convenience method to allow subtypes to know when they should fire a
	 * value remove event in a null-safe manner.
	 * 
	 * @param <I>
	 *            value type
	 * @param source
	 *            the source
	 * @param container
	 *            the container to add the value to, may be null
	 * @param valueToBeAdded
	 *            the new value to be added to the given container, may be null
	 * @return whether the event should be fired, because the value is not yet
	 *         in the container
	 */
	protected static <T> boolean shouldFire(HasValueAddedHandlers<T> source, Collection<T> container, T valueToBeAdded,
		boolean valuesHaveToBeUnique, boolean valuesCanBeNull, Long maxSize) {
		return getType() != null && container != null && (!valuesHaveToBeUnique || !container.contains(valueToBeAdded))
			&& (valuesCanBeNull || valueToBeAdded != null) && (maxSize == null || container.size() < maxSize);
	}

	/**
	 * Convenience method to allow subtypes to know when they should fire a
	 * value remove event in a null-safe manner.
	 * 
	 * @param <I>
	 *            value type
	 * @param source
	 *            the source
	 * @param container
	 *            the container to add the value to, may be null
	 * @param valueToBeAdded
	 *            the new value to be added to the given container, may be null
	 * @return whether the event should be fired, because the value is not yet
	 *         in the container
	 */
	protected static <T> boolean shouldFire(HasValueAddedHandlers<T> source, List<T> container, T valueToBeAdded,
		int index, boolean valuesHaveToBeUnique, boolean valuesCanBeNull, Long maxSize) {
		return getType() != null && container != null && index >= 0 && index < container.size()
			&& (!valuesHaveToBeUnique || !container.contains(valueToBeAdded))
			&& (valuesCanBeNull || valueToBeAdded != null) && (maxSize == null || container.size() < maxSize);
	}

	private final T value;

	/**
	 * Creates a value change event.
	 * 
	 * @param value
	 *            the value
	 */
	protected ValueAddedEvent(T value) {
		this.value = value;
	}

	// The instance knows its BeforeSelectionHandler is of type I, but the TYPE
	// field itself does not, so we have to do an unsafe cast here.
	@SuppressWarnings("unchecked") @Override public final Type<ValueAddedHandler<T>> getAssociatedType() {
		return (Type) getType();
	}

	/**
	 * Gets the value.
	 * 
	 * @return the value
	 */
	public T getValue() {
		return value;
	}

	@Override public String toDebugString() {
		return super.toDebugString() + getValue();
	}

	@Override protected void dispatch(ValueAddedHandler<T> handler) {
		handler.onValueAdded(this);
	}
}
